/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JP_RegistrarMasivo.java
 *
 * Created on Jul 15, 2009, 4:41:23 PM
 */

package gui.tabbedpane;

import delegate.GestionDelegate;
import controlacciones.ejb3.entity.TbCliente;
import controlacciones.ejb3.entity.TbDatosCliente;
import gui.JP_ClienteMasivo;
import helper.Utiles_Panel;
import javax.swing.JButton;
import javax.swing.JDialog;
import org.jdesktop.application.FrameView;
import helper.JP_Modelo;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFileChooser;
import helper.Utiles_Importar;
import helper.Utiles_MensajesDialogo;
import helper.Utiles_Varios;
import org.jdesktop.application.Action;

import org.jdesktop.application.Task;
/**
 *
 * 
 */
public class JP_Masivo extends JP_Modelo {

    /** Creates new form JP_RegistrarMasivo */
    public JP_Masivo() {
        inicializaComponentes();
        
    }

    private void inicializaComponentes(){
        initComponents();
        listaClientes = new ArrayList(1);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jp_Derechohabientes = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbClientes = new javax.swing.JTable();
        btnImportar = new javax.swing.JButton();
        btnAgregar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();

        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class).getContext().getResourceMap(JP_Masivo.class);
        jp_Derechohabientes.setBorder(javax.swing.BorderFactory.createTitledBorder(null, resourceMap.getString("jp_Derechohabientes.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, resourceMap.getFont("jp_Derechohabientes.border.titleFont"))); // NOI18N
        jp_Derechohabientes.setName("jp_Derechohabientes"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        tbClientes.setAutoCreateRowSorter(true);
        tbClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        tbClientes.setName("tbClientes"); // NOI18N
        jScrollPane1.setViewportView(tbClientes);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class).getContext().getActionMap(JP_Masivo.class, this);
        btnImportar.setAction(actionMap.get("cargarArchivo")); // NOI18N
        btnImportar.setFont(resourceMap.getFont("btnImportar.font")); // NOI18N
        btnImportar.setIcon(resourceMap.getIcon("btnImportar.icon")); // NOI18N
        btnImportar.setText(resourceMap.getString("btnImportar.text")); // NOI18N
        btnImportar.setName("btnImportar"); // NOI18N

        btnAgregar.setFont(resourceMap.getFont("btnAgregar.font")); // NOI18N
        btnAgregar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/resources/images/add-page-blue.gif"))); // NOI18N
        btnAgregar.setText(resourceMap.getString("btnAgregar.text")); // NOI18N
        btnAgregar.setName("btnAgregar"); // NOI18N
        btnAgregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAgregarActionPerformed(evt);
            }
        });

        btnEliminar.setFont(resourceMap.getFont("btnEliminar.font")); // NOI18N
        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/resources/images/delete-page-red.gif"))); // NOI18N
        btnEliminar.setText(resourceMap.getString("btnEliminar.text")); // NOI18N
        btnEliminar.setName("btnEliminar"); // NOI18N
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        btnModificar.setFont(resourceMap.getFont("btnModificar.font")); // NOI18N
        btnModificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/resources/images/edit-page-blue.gif"))); // NOI18N
        btnModificar.setText(resourceMap.getString("btnModificar.text")); // NOI18N
        btnModificar.setEnabled(false);
        btnModificar.setName("btnModificar"); // NOI18N
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jp_DerechohabientesLayout = new javax.swing.GroupLayout(jp_Derechohabientes);
        jp_Derechohabientes.setLayout(jp_DerechohabientesLayout);
        jp_DerechohabientesLayout.setHorizontalGroup(
            jp_DerechohabientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jp_DerechohabientesLayout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 476, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jp_DerechohabientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnImportar, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                    .addComponent(btnAgregar, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                    .addComponent(btnEliminar, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE)
                    .addComponent(btnModificar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE))
                .addContainerGap())
        );
        jp_DerechohabientesLayout.setVerticalGroup(
            jp_DerechohabientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jp_DerechohabientesLayout.createSequentialGroup()
                .addGroup(jp_DerechohabientesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jp_DerechohabientesLayout.createSequentialGroup()
                        .addComponent(btnImportar)
                        .addGap(4, 4, 4)
                        .addComponent(btnAgregar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnModificar))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jp_Derechohabientes, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jp_Derechohabientes, javax.swing.GroupLayout.DEFAULT_SIZE, 192, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void cargaTabla(){
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();
        jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listaClientes, this.tbClientes);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${numInscrip}"));
        columnBinding.setColumnName("NumInscrip");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);

        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding1 = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombre}"));
        columnBinding1.setColumnName("Nombre");
        columnBinding1.setColumnClass(String.class);
        columnBinding1.setEditable(false);
        
        bindingGroup.addBinding(jTableBinding);
        bindingGroup.bind();
    }

    public void refrescarTabla(){
        try{
            this.bindingGroup.removeBinding(jTableBinding);
        }catch( Exception e ){

        }
        this.cargaTabla();
    }

    public void agregaCliente( TbCliente cli ){
        listaClientes.add( cli );
    }

    public void eliminaCliente( TbCliente cli ){
        listaClientes.remove(cli);
    }
  
    public List<TbCliente> getListaClientes() {
        return listaClientes;
    }

    public JButton getBtnImportar() {
        return btnImportar;
    }
 
    public void setListaClientes(List<TbCliente> listaClientes) {
        this.listaClientes = listaClientes;
    }

    public void limpiarLista(){
        this.listaClientes.clear();
        this.refrescarTabla();
    }

    private void btnAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAgregarActionPerformed
        JP_ClienteMasivo panel = new JP_ClienteMasivo();
        System.out.println("getRef: " + getRef());
        JDialog frDiag = Utiles_Panel.creaVentanaDialogo( null , panel, "Registrar Cliente");
//        JDialog frDiag = Utiles_Panel.creaVentanaDialogo(((FrameView) getRef()).getFrame(), panel, "Registrar Cliente");
        panel.setPadre(Utiles_Panel.TIPO_JDIALOG, frDiag);
        panel.setRef(getRef()); //Paso referencia de contexto
        panel.setRefDep(this); //Paso referencia de contexto dependiente
        frDiag.pack();
        frDiag.setVisible(true); //Hago visible el JDialog        
    }//GEN-LAST:event_btnAgregarActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        JP_ClienteMasivo panel = new JP_ClienteMasivo();
        JDialog frDiag = Utiles_Panel.creaVentanaDialogo(((FrameView) getRef()).getFrame(), panel, "Registrar Cliente");
        panel.setPadre(Utiles_Panel.TIPO_JDIALOG, frDiag);
        panel.setRef(getRef()); //Paso referencia de contexto
        panel.setRefDep(this); //Paso referencia de contexto dependiente
        frDiag.pack();
        frDiag.setVisible(true); //Hago visible el JDialog
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        int x = -1;
        try{
            x = tbClientes.convertRowIndexToModel( tbClientes.getSelectedRow() );
        }catch( Exception er ){
            return;
        }
        listaClientes.remove(x);
        this.refrescarTabla();
    }//GEN-LAST:event_btnEliminarActionPerformed

    @Action
    public Task cargarArchivo(){
        JFileChooser jfc = new JFileChooser();
        jfc.setMultiSelectionEnabled( false );
        if( ruta != null ){
            jfc.setCurrentDirectory(new File(ruta));
        }
        int returnVal = jfc.showOpenDialog( this );
        if( returnVal == JFileChooser.APPROVE_OPTION ){
            File arch = new File( jfc.getSelectedFile().toString() );
            this.ruta = arch.getParent(); //Asignamos la ruta guardando temporalmente la ruta donde nos hemos quedado
            return new CargaArchivo(org.jdesktop.application.Application.getInstance(controlaccionescomercial.ControlAccionesComercialApp.class), arch);
        }else{
            return null;
        }
        
    }

    private class CargaArchivo extends org.jdesktop.application.Task<Object, Void> {
        CargaArchivo(org.jdesktop.application.Application app, File f) {
            super(app);
            this.file = f;
        }
        @Override protected Object doInBackground() {
            importarArchivo( file );
            return null;  // return your result
        }
        @Override protected void succeeded(Object result) {
        }
        File file;
    }
    
    //Procedimiento en Segundo plano
    private void importarArchivo( File f ){
        Utiles_Importar utiles_importar = new Utiles_Importar( f );
        try{
            List dat = utiles_importar.getDatosHoja(0); //Definimos obtener los datos de la hoja 0
            int bloqueDatos = 10000;
            int inicio = 0;
            List listTemp;
            List<TbDatosCliente> datosClientes = new ArrayList(1);
            System.out.println( "Antes de bucle: " + inicio );

            while( dat.size() > inicio + bloqueDatos ){
                listTemp = new ArrayList(1);
                for( int i = inicio; i < inicio + bloqueDatos; i++ ){
                    listTemp.add(dat.get(i));
                }
                System.out.println( "Valor de variable: " + inicio );

                datosClientes.addAll( GestionDelegate.getInstance().getDatosClientes( listTemp ) );
                inicio += bloqueDatos;

            }
            System.out.println( "Despues de bucle: " + inicio );

            if( inicio - bloqueDatos < dat.size() ){
                if(inicio - bloqueDatos < 0 ){
                    inicio = 0;
                }
                listTemp = new ArrayList(1);
                for( int i = inicio; i < dat.size(); i++ ){
                    listTemp.add(dat.get(i));
                }
                datosClientes.addAll( GestionDelegate.getInstance().getDatosClientes( listTemp ) );
            }

            this.listaClientes.clear();
            TbCliente temp = null;

            for( TbDatosCliente datCliente : datosClientes ){
                temp =  new TbCliente();
                String num_inscrip = "";

                if( datCliente != null ){
                    num_inscrip = datCliente.getNumInscrip();
                }
                temp.setNumInscrip(num_inscrip);
                temp.setNombre(datCliente.getNombre());
                temp.setDireccion(datCliente.getDireccion());

                this.listaClientes.add( temp );
            }

            Utiles_Varios.centraCeldasTabla( this.tbClientes );
        }catch( Exception er ){
            Utiles_MensajesDialogo.mensajeAlerta( "Verifique si el archivo que desea cargar es el correcto" );
            er.printStackTrace();
        }
        this.refrescarTabla();
    }

    @Override
    public void setEnabled( boolean b ){
        super.setEnabled(b);
        this.btnAgregar.setEnabled(b);
        this.btnEliminar.setEnabled(b);
        this.btnImportar.setEnabled(b);
        //this.btnModificar.setEnabled(b);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAgregar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnImportar;
    private javax.swing.JButton btnModificar;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel jp_Derechohabientes;
    private javax.swing.JTable tbClientes;
    // End of variables declaration//GEN-END:variables
    private List<TbCliente> listaClientes;

    private org.jdesktop.swingbinding.JTableBinding jTableBinding;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;

    private String ruta;
}
